//
//  HLHomeVideoViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/30.
//

#import "HLHomeVideoViewController.h"
#import "HLUserDetailViewController.h"
#import "HLHomeListRequest.h"
#import "HLHomeVideoCell.h"
#import "HLVideoListRequest.h"
#import <SJVideoPlayer/SJVideoPlayer.h>

@interface HLHomeVideoViewController ()

@property (nonatomic, strong) HLHomeLabelModel *label;
@property (nonatomic, strong) SJVideoPlayer *player;
@property (nonatomic, strong) HLHomeVideoCell *currentCell;

@end

@implementation HLHomeVideoViewController

- (instancetype)initWithLabel:(HLHomeLabelModel *)label;
{
    self = [super init];
    if (self){
        self.label = label;
        self.player = [SJVideoPlayer lightweightPlayer];
    }
    return self;
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:HLVideoViewDidChangeNotification object:@(YES)];
    [_player vc_viewDidAppear];
    if (!self.request){
        self.request = [[HLVideoListRequest alloc] init];
        self.request.delegate = self;
        [self requestInit];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player vc_viewWillDisappear];
}


- (void)viewDidDisappear:(BOOL)animated
{
    [_player vc_viewDidDisappear];
    [[NSNotificationCenter defaultCenter] postNotificationName:HLVideoViewDidChangeNotification object:@(NO)];
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:HLUserFollowDidChangeNotification object:nil];
    
    SJVideoPlayer.updateResources(^(id<SJVideoPlayerControlLayerResources>  _Nonnull resources) {
        resources.bottomIndicatorTraceColor = HLMainColor;
        resources.replayImage = UIImageMake(@"user_detail_cell_play");
        resources.placeholder = [HLUIHelper avatarBigPlaceholder];
        resources.replayTitleColor = UIColorClear;
    });
    
    MJWeakSelf
    _player.playbackObserver.playbackDidFinishExeBlock = ^(__kindof SJVideoPlayer * _Nonnull playerControl) {
        [weakSelf.player replay];
    };
    
    _player.playbackObserver.playbackStatusDidChangeExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull player) {
        if ([weakSelf.player isPaused]){
            [weakSelf.currentCell stopVideo];
        } else {
            [weakSelf.currentCell playVideo];
        }
    };
    [_player.controlLayerAppearManager keepDisappearState];
    _player.controlLayerAppearManager.disabled = YES;
    _player.defaultEdgeControlLayer.bottomContainerView.hidden = YES;
}

- (void)_playVideo
{
    self.currentCell = [[self.collectionView visibleCells] firstObject];
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:self.currentCell];
    [self.currentCell invaiteVideo];
    HLUserVideoModel *video = self.datasources[indexPath.row];
    SJPlayModel *playModel = [SJPlayModel playModelWithCollectionView:self.collectionView indexPath:indexPath superviewSelector:@selector(playerSuperview)];
    _player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:[NSURL URLWithString:video.shortVideoLink] playModel:playModel];
    [_player.presentView.placeholderImageView sd_setImageWithURL:[NSURL URLWithString:video.imgLink]];
    [_player play];
}

- (void)requestInit
{
    [self showEmptyView];
    [self.emptyView.loadingView startAnimating];
    [self.emptyView setTextLabelText:@"加载中..."];
    [self.request start];
}

- (void)initCollectionView
{
    [super initCollectionView];

    CGFloat height = SCREEN_HEIGHT-TabBarHeight;
    QMUICollectionViewPagingLayout *layout = [[QMUICollectionViewPagingLayout alloc] initWithStyle:QMUICollectionViewPagingLayoutStyleScale];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, height);
    layout.minimumLineSpacing = 0.0;
    layout.minimumInteritemSpacing = 0.0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    [self headerRefresh];
    [self footerRefresh];
    [self.collectionView registerClass:[HLHomeVideoCell class] forCellWithReuseIdentifier:[HLHomeVideoCell identifyCell]];
    [self.collectionView setCollectionViewLayout:layout];
    [self.collectionView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor = UIColorBlack;
    self.collectionView.automaticallyAdjustsScrollIndicatorInsets = NO;
    self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datasources.count;
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    HLHomeVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[HLHomeVideoCell identifyCell] forIndexPath:indexPath];
    [cell.playButton addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [cell.videoButton addTarget:self action:@selector(videoAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.wantButton addTarget:self action:@selector(videoAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.model = self.datasources[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self _playVideo];
}

- (void)playAction
{
    [_player play];
}

- (void)videoAction:(QMUIButton *)btn
{
    if (_player.isPlaying){
        [_player pause];
    }
    
    HLUserInfoModel *user = [[HLUserInfoModel alloc] init];
    user.userId = self.currentCell.model.userId;
    [HLUIHelper callWithUser:user];
}


- (void)headerRefresh
{
    HLVideoListRequest *videoRequest = (HLVideoListRequest *)self.request;
    videoRequest.page = 1;
    [self.request start];
}

- (void)footerRefresh
{
    HLVideoListRequest *videoRequest = (HLVideoListRequest *)self.request;
    videoRequest.page += 1;
    [self.request start];
}

- (void)requestFinished:(__kindof YTKBaseRequest *)request
{
    [super requestFinished:request];
    
    HLVideoListRequest *videoRequest = (HLVideoListRequest *)request;
    
    if (videoRequest.page == 1){
        [self.datasources removeAllObjects];
    }
    
    NSArray *videoList = [videoRequest videoList];
    [self.datasources addObjectsFromArray:videoList];
    if (videoList.count < [HLListPageSize integerValue] && self.datasources.count > 0){
        [self noMordDataWithFooterRefresh];
    }
    
    if (self.datasources.count == 0){
        [self.emptyView setLoadingViewHidden:YES];
        [self.emptyView setImage:UIImageMake(@"empty_icon_2")];
        [self.emptyView setTextLabelText:@"空空如也"];
        [self.emptyView setDetailTextLabelText:[NSString stringWithFormat:@"哇哦，%@页面一个视频也没有", _label.tagName]];
    } else {
        [self hideEmptyView];
    }
    
    [self.collectionView reloadData];
    if (self.datasources.count > 0){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self _playVideo];
        });
    }
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    [super requestFailed:request];
}

- (void)notification:(NSNotification *)noti
{
    NSDictionary *info = noti.object;
    NSInteger type = [[info objectForKey:@"type"] intValue];
    NSString *user = [info objectForKey:@"user"];
    
    if (![user isEqualToString:self.currentCell.model.userId]){
        return;
    }
    
    if (type == HLUserOptionTypeFollow){
        self.currentCell.model.isFollow = @"1";
        self.currentCell.followButton.hidden = YES;
    } else {
        self.currentCell.model.isFollow = @"0";
        self.currentCell.followButton.hidden = NO;
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - JXCategoryListContentViewDelegate

/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}


@end
